const { ethers } = require("ethers");

/**
 * 验证合约在真实网络上的部署情况
 * 可以查看任何网络上的合约状态
 */
async function main() {
    console.log("🔍 验证合约部署情况\n");
    
    // 配置要检查的网络和合约
    const networks = [
        {
            name: "Sepolia",
            rpc: "https://ethereum-sepolia-rpc.publicnode.com",
            chainId: 11155111,
            explorer: "https://sepolia.etherscan.io"
        },
        {
            name: "Goerli", 
            rpc: "https://goerli.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161",
            chainId: 5,
            explorer: "https://goerli.etherscan.io"
        }
    ];
    
    // 要检查的合约地址（示例）
    const contractAddresses = [
        "0x5FbDB2315678afecb367f032d93F642f64180aa3", // 本地部署的地址
        // 添加其他已部署的合约地址
    ];
    
    for (const network of networks) {
        console.log(`🌐 检查 ${network.name} 网络:`);
        console.log(`RPC: ${network.rpc}`);
        console.log(`浏览器: ${network.explorer}\n`);
        
        try {
            const provider = new ethers.JsonRpcProvider(network.rpc);
            const networkInfo = await provider.getNetwork();
            
            console.log(`✅ 网络连接成功 (Chain ID: ${networkInfo.chainId})`);
            
            for (const contractAddress of contractAddresses) {
                console.log(`\n🔍 检查合约: ${contractAddress}`);
                
                try {
                    // 检查合约是否存在
                    const code = await provider.getCode(contractAddress);
                    
                    if (code === "0x") {
                        console.log("❌ 合约不存在（没有字节码）");
                        continue;
                    }
                    
                    console.log("✅ 合约存在");
                    console.log(`📋 字节码长度: ${code.length} 字符`);
                    
                    // 尝试与合约交互（需要ABI）
                    try {
                        const AuctionNFT = await ethers.getContractFactory("AuctionNFT");
                        const contract = new ethers.Contract(contractAddress, AuctionNFT.interface, provider);
                        
                        // 查询基本信息
                        const name = await contract.name();
                        const symbol = await contract.symbol();
                        const owner = await contract.owner();
                        const totalSupply = await contract.getTotalSupply();
                        
                        console.log(`📝 合约名称: ${name}`);
                        console.log(`🏷️  合约符号: ${symbol}`);
                        console.log(`👤 合约拥有者: ${owner}`);
                        console.log(`📊 总供应量: ${totalSupply}`);
                        
                        // 生成浏览器链接
                        console.log(`🔗 浏览器链接: ${network.explorer}/address/${contractAddress}`);
                        
                        // 查询最近的交易
                        console.log("\n📈 最近活动:");
                        const currentBlock = await provider.getBlockNumber();
                        const events = await contract.queryFilter("NFTMinted", currentBlock - 1000, currentBlock);
                        
                        if (events.length > 0) {
                            console.log(`发现 ${events.length} 个铸造事件:`);
                            events.slice(-3).forEach((event, index) => {
                                console.log(`  ${index + 1}. TokenId: ${event.args.tokenId}, 接收者: ${event.args.to}`);
                            });
                        } else {
                            console.log("暂无铸造活动");
                        }
                        
                    } catch (interactionError) {
                        console.log("⚠️  合约存在但无法交互（可能不是AuctionNFT合约）");
                        console.log(`错误: ${interactionError.message}`);
                    }
                    
                } catch (contractError) {
                    console.log(`❌ 检查合约失败: ${contractError.message}`);
                }
            }
            
        } catch (networkError) {
            console.log(`❌ 连接 ${network.name} 失败: ${networkError.message}`);
        }
        
        console.log("─".repeat(60));
    }
    
    console.log("\n📋 如何查看真实部署情况:");
    console.log("1. 🌐 区块链浏览器 - 最直观的方式");
    console.log("   • 查看合约代码、交易历史、事件日志");
    console.log("   • Sepolia: https://sepolia.etherscan.io");
    console.log("   • Mainnet: https://etherscan.io");
    
    console.log("\n2. 🔧 编程方式查询");
    console.log("   • 使用ethers.js连接真实网络");
    console.log("   • 调用合约的只读函数");
    console.log("   • 监听合约事件");
    
    console.log("\n3. 🎯 前端集成");
    console.log("   • 通过MetaMask等钱包连接");
    console.log("   • 在DApp中显示合约数据");
    console.log("   • 用户直接与合约交互");
    
    console.log("\n4. 📊 分析工具");
    console.log("   • Dune Analytics - 数据分析");
    console.log("   • The Graph - 索引和查询");
    console.log("   • Moralis - API服务");
}

main()
    .then(() => process.exit(0))
    .catch((error) => {
        console.error("❌ 验证失败:", error);
        process.exit(1);
    });